/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package researchgrants.utils;

import java.awt.Component;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.SortedMap;
import javax.swing.DefaultListModel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ChangeEvent;
import researchgrants.parts.LoggedData.panels.events.ChangeEventHandler;
import javax.swing.event.ChangeListener;

/**
 *
 * @author DOStudent1
 */
public class MultiSelectList implements ChangeEventHandler{

    private SortedMap<?extends Object, String> map;
    private JCheckBoxList listComponent;
    
    
    public MultiSelectList(SortedMap<? extends Object, String> map) {
        this.map = map;
        listComponent=new JCheckBoxList();
        
        DefaultListModel defModel = new DefaultListModel();
        listComponent.setModel (defModel);
        for (Iterator<String> it = map.values().iterator(); it.hasNext();) {
            Object object = it.next();
            defModel.addElement(object);
        }
        
        listComponent.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                notifyChangeListeners();
            }
        });
        
    }
    
    public Component getComponent() {
        JScrollPane pane=new JScrollPane(listComponent);
        pane.setAutoscrolls(true);
        listComponent.setVisibleRowCount(3);
//        pane.setPreferredSize(new Dimension(100, listComponent.getP*4));
        return(pane);
    }
    
    @SuppressWarnings("unchecked")
    public Collection<Object> getSelectedKeys() {
        int[] selectedIndices = listComponent.getSelectedIndices();
        Object[] selectedKeys=new Object[selectedIndices.length];
        int selectedIndexIndex=0;
        int i=0;
        Iterator<Object> iteratorKeys =  (Iterator<Object>) map.keySet().iterator();
        while ((iteratorKeys.hasNext()) && (selectedIndexIndex<selectedIndices.length)){
            Object key = iteratorKeys.next();
            if (selectedIndices[selectedIndexIndex]==i) {
                selectedKeys[selectedIndexIndex]=key;
                selectedIndexIndex++;
            }
            i++;
        }
        return(Arrays.asList(selectedKeys));
    }
    
    
    private Collection<ChangeListener> changeEventListeners=new LinkedList<ChangeListener>();
    public void addChangeListener(ChangeListener changeEventListener) {
        changeEventListeners.add(changeEventListener);
    }
    
    private void notifyChangeListeners() {
        for (Iterator<ChangeListener> it = changeEventListeners.iterator(); it.hasNext();) {
            ChangeListener changeEventListener = it.next();
            changeEventListener.stateChanged(new ChangeEvent(this));
        }
    }
}
